// 获取应用实例
const app = getApp()
import {
    getNewProject,
    getNewProjectWorker,
    newDayExportWorkerList,
    deleteWorker,
    cancelInsure,
    getInsurancePdf,
    addToProjectFromBook,
    confirmInsure,
    getUserInfo
} from '../../../api/app.js'
import {
    determineInsure,
    manualAddWorker,
    expressInsurance,
    getInsurePlan,
    getInsuranceEnterprise
} from '../../api/insurance'
import {
    inputchange,
    toast,
    confirm,
    openDocument
} from '../../../utils/util.js'
import user from '../../../utils/user.js'
// import Socket from '../../../api/socket.js'

const toastHistory = []
let pageNum = 1,
    notPage = false,
    searchValue = ''

Page({
    data: {
        top: app.globalData.menuTop,
        workers: [],
        date: '',
        companyName: '',
        companyId: '',
        recipient: '',
        projectName: '',
        projectNum: '',
        leader: [],
        women: 0,
        men: 0,
        workerCount: 0,
        morePosition: 0,
        showMoreStatus: false,
        projectId: 0,
        showGodAddStatus: false,
        invitationStatus: false,
        copyLinkStatus: false,
        copyLinkContent: '',
        isOld: false,
        clockStartTime: '',
        clockEndTime: '',
        clockAddress: '',
        staffUnderpay: 0,
        setStaffUnderpayStatus: false,
        dayNightFlag: 0,
        signInType: '',
        collect: [],
        isOpenWesure: false,
        wesureIsDelete: false,
        isTipInsurance: false,
        tipTop: 0,
        wesureState: 0, // 控制我要投保按钮 是否可以点击
        createUserId: '',
        isManualAdd: false,
        already: [],
        pageNum: 1,
        hasNextPage: Boolean,
        isAgain: 0,
        insureCompanyType: '',
        isDeleteSeverCompany: 0,
        industryPlanId: ''
    },
    onLoad(options) {
        user.waitLogin().then((user) => {
            console.log(user, 'addadd')
            this.setData({
                insureCompanyType: user.insureCompanyType
            })
            console.log(options, 'options')
            if (options.isAgain === 5) {
                console.log(options.isAgain, '打印了这个是什么？？？')
                let value = 0
                this.setData({
                    wesureState: value,
                    projectId: options.id,
                    isAgain: 5
                }, () => {
                    console.log(this.data.wesureState, '打印了这个是什么2222222222222222')
                })
            } else {
                this.setData({
                    projectId: options.id,
                })
            }
        })
    },
    onShow() {
        user.waitLogin().then(() => {
            this.setData({
                workers: [],
                pageNum: 1,

            })
            // if(this.data.isAgain === 5){
            //     this.getProject(isAgain == 5)
            //     this.getProjectWorker(notPage = false)
            // }else{
            this.getProject()
            this.getProjectWorker(notPage = false)
            // }

        })
    },
    onUnload() {
        pageNum = 1
        notPage = false
        searchValue = ''
        // this.data.socket.close()
        // this.getProjectWorker()
    },
    getProject(isAgain) {
        getNewProject({
            id: this.data.projectId
        }).then((res) => {
            // 判断是否为当天之前的项目
            const isOld = new Date(res.createTime).getTime() < new Date(new Date().toLocaleDateString()).getTime()
            console.log(res, '哈哈哈哈哈')
            this.setData({
                date: res.date,
                companyName: res.serveCompanyName,
                companyId: res.serveCompanyId,
                industryPlanId: res.industryPlanId,
                projectName: res.projectName,
                projectNum: res.projectNum,
                recipient: res.recipient,
                clockStartTime: res.signTimeStart,
                clockEndTime: res.signTimeEnd,
                clockAddress: res.signPlace,
                staffUnderpay: res.staffUnderpay,
                setStaffUnderpay: '',
                isOld,
                dayNightFlag: res.dayNightFlag,
                signInType: res.signInType,
                isOpenWesure: res.isOpenWesure,
                wesureIsDelete: res.serverCompanyIsDelete,
                wesureTypeName: res.wesureTypeName,
                wesureInfo: res.wesureInfo,
                expiredTimeGSC: res.expiredTimeGSC,
                wesureState: res.wesureState,
                createUserId: res.createUserId,
                isDeleteSeverCompany: res.isDeleteSeverCompany
            }, () => {
                console.log(this.data.companyName, '呵呵呵呵')
                if (this.data.isAgain == 5) {
                    this.setData({
                        wesureState: 0
                    })
                }
            })
            if (res.isOpenWesure) {
                this.insuranceTime()
            }
        })
    },

    // 获取员工列表
    getProjectWorker() {
        console.log(notPage, '调用拉吗')
        if (notPage) {
            return
        }
        getNewProjectWorker({
            projectId: this.data.projectId,
            searchText: searchValue,
            pageSize: 10,
            pageNum: this.data.pageNum,
        }).then(res => {
            console.log(res, '哈哈哈哈哈哈哈哈')
            if (this.data.workers.length == 0) {
                pageNum = 1
            }
            pageNum += 1
            if (!res.hasNextPage) {
                notPage = true
            }
            let already
            for (const i in res.list) {
                // + '（' + res.list[i].idCardNo.slice(-4) + '）'
                // res.list[i].workerName = res.list[i].workerName 
                res.list[i].showAll = false
                res.list[i].key = res.list[i].id + '处理中'
                already = res.list[i].alreadyInsuredProjectId
            }
            this.data.workers.push(...res.list)
            this.setData({
                workers: this.data.workers,
                women: res.women,
                men: res.men,
                workerCount: res.count,
                already: already,
                pageNum: pageNum
            }, () => {
                console.log(this.data.workers, 'workers')
            })
        })
    },

    getPeople() {
        //   if(!this.data.hasNextPage){
        this.getProjectWorker()
        //   }
    },

    insuranceTime() {
        // todo: 需要性能优化时，将需要修改的所有数据放入一个数组中，实现一次setData修改整体界面
        setInterval(() => {
            this.data.workers.forEach((item, index) => {
                if (item.countDown === 0) {
                    this.data.workers[index].policyStatus = this.data.workers[index].policyStatus || '处理中'
                    this.data.workers[index].key = this.data.workers[index].id + '处理中'
                    this.data.workers[index].countDown = false
                    confirmInsure({
                        authRecordId: this.data.workers[index].payrollCardRecordId
                    })
                }
                if (item.countDown) {
                    this.data.workers[index].countDown = item.countDown - 1
                }
            })
            this.setData({
                workers: this.data.workers
            })
        }, 1000)
    },
    // 搜索员工
    searchWorker(event) {
        notPage = false
        searchValue = event.detail.value,
            this.setData({
                workers: [],
                pageNum: 1,
            })
        this.getProjectWorker()
    },
    // 显示更多
    showMore(event) {
        const index = event.currentTarget.dataset.index
        const list = []
        // if (this.data.isOpenWesure && (this.data.workers[index].policyStatus === '保障中' || this.data.workers[index].policyStatus === '已失效')) {
        //     list.push({
        //         text: '查看保单',
        //         key: index,
        //         icon: '/assets/img/preview.png',
        //         bind: 'preview'
        //     })
        // }
        if (event.currentTarget.dataset.phone)
            list.push({
                text: '电话',
                key: event.currentTarget.dataset.phone,
                icon: '/assets/img/call.png',
                bind: 'call'

            })
        list.push({
            text: '删除',
            key: index,
            icon: '/assets/img/delete.png',
            bind: 'delete'
        })
        this.setData({
            'moreList': list
        })
        this.setData({
            morePosition: event.touches[0].clientY + 6,
            showMoreStatus: true
        })
    },
    // 隐藏显示更多
    hideMore() {
        this.setData({
            showMoreStatus: false
        })
    },
    inputchange(event) {
        inputchange(event, this)
    },


    // 打电话
    call(event) {
        wx.makePhoneCall({
            phoneNumber: event.detail
        })
    },
    // 标记大神
    markGod(event) {
        console.log(this.data.workers)
        this.setData({
            showGodAddStatus: true,
            godBasicMsg: this.data.workers[event.detail]
        })
    },
    // 删除员工
    deleteWorker(event) {
        app.confirm('是否删除该员工?').then(() => {
            console.log(event, 'eventevent111111111')
            deleteWorker({
                id: this.data.workers[event.currentTarget.dataset.index].id
            }).then(() => {
                app.toast('删除成功!', 'success')
                setTimeout(() => {
                    pageNum = 1
                    notPage = false
                    this.setData({
                        workers: [],
                        pageNum: pageNum
                    })
                    this.getProjectWorker()
                }, 1000)
            })
        })
    },
    // 添加大神成功回调
    addGodComplete() {
        pageNum = 1
        notPage = false
        this.getProjectWorker()
        this.setData({
            showGodAddStatus: false,
        })
    },
    // 隐藏添加大神弹窗
    hideGodAdd() {
        this.setData({
            showGodAddStatus: false
        })
    },
    // 显示邀请弹窗
    showInvitation() {
        this.setData({
            invitationStatus: true
        })
    },

    // 隐藏邀请弹窗
    hideInvitation() {
        this.setData({
            invitationStatus: false
        })
    },

    // 前往从通讯录添加员工界面
    addWorkerFromBook() {
        wx.navigateTo({
            url: '/packagePay/pages/book-add/book-add?projectId=' + this.data.projectId + '&companyId=' + this.data.companyId,
            events: {
                acceptDataFromOpenedPage: (data) => {
                    console.log(data, 'datadatadata')
                    addToProjectFromBook({
                        projectId: this.data.projectId,
                        serveCompanyId: this.data.companyId,
                        addressBookIds: data.data
                    }).then(() => {
                        app.toast('添加成功')
                        pageNum = 1
                        notPage = false
                        this.setData({
                            workers: []
                        })
                        this.getProjectWorker()
                    })
                },
            }
        })
    },

    // 前往邀请码邀请员工界面
    goInvitationCode() {
        this.setData({
            invitationStatus: false
        })
        wx.navigateTo({
            url: '/packagePay/pages/invitation-code/invitation-code?projectName=' + this.data.projectName + '&projectId=' + this.data.projectId
        })
    },
    // 前往二维码邀请管理员界面
    goMasterInvitationQrCode() {
        this.setData({
            invitationStatus: false
        })
        wx.navigateTo({
            url: '/packagePay/pages/master-invitation-qrcode/master-invitation-qrcode?projectId=' + this.data.projectId + '&projectName=' + this.data.projectName
        })
    },
    // 海报邀请员工界面
    goInvitationPoster() {
        wx.navigateTo({
            url: '/packagePay/pages/invitation-poster/invitation-poster?projectName=' + this.data.projectName + '&projectId=' + this.data.projectId + '&poster=4' + '&type=5'
        })
    },
    onExamine(event) {
        let id = event.currentTarget.dataset.id
        wx.navigateTo({
            url: '/packageInsurance/pages/insurance-insure-detail/insurance-insure-detail?id=' + id + '&showmore=' + true,
        })
    },
    // 导出名单
    exportWorkerList() {
        newDayExportWorkerList({
            projectId: this.data.projectId
        }).then(res => {
            console.log(res, '导出名单导出名单')
            const url = app.globalData.baseUrl + '/common/download?fileName=' + res +
                '&delete=false'
            console.log(url)
            if (wx.canIUse('openDocument')) {
                const projectName = this.data.projectName.replace(/\//g, '.') + '.xlsx'
                openDocument(url, projectName).then(() => {}, () => {
                    this.setData({
                        copyLinkStatus: true,
                        copyLinkContent: url
                    })
                })
            } else {
                this.setData({
                    copyLinkStatus: true,
                    copyLinkContent: url
                })
            }
        })
    },
    // 复制名单下载链接
    copyWorkerListLink() {
        const t = this
        wx.setClipboardData({
            data: this.data.companyName + '\r\n' + this.data.copyLinkContent,
            success() {
                t.setData({
                    copyLinkStatus: false
                })
            }
        })
    },
    // 显示发单政策
    tipPolicy() {
        wx.showModal({
            title: '政策内容',
            content: this.data.billingPolicy,
            showCancel: false,
        })
    },
    // 复制链接
    hideCopyLink() {
        this.setData({
            copyLinkStatus: false
        })
    },
    // 取消
    cancelSetStaffUnderpay() {
        this.setData({
            setStaffUnderpayStatus: false
        })
    },

    // 前往用户个人信息界面
    onGoWorker(event) {
        console.log(event.currentTarget.dataset.islogout, 'events')
        if (event.currentTarget.dataset.islogout !== 0) {
            toast('该用户已注销')
            return
        }
        const workerId = event.currentTarget.dataset.id
        wx.navigateTo({
            url: '/pages/worker/index/index?id=' + workerId
        })
    },
    onShareAppMessage() {
        return {
            title: user.userName + '邀请您加入「' + (this.data.projectName || user.companyName) + '」' + (this.data.projectName ? '名单管理' : '项目'),
            path: '/pages/index/index?scene=' + encodeURIComponent('uId=' + user.userId + '&cId=' + user.companyId + (this.data.projectId ?
                ('&pId=' + this.data.projectId) : '')),
            imageUrl: '/packagePay/assets/img/resident/share.png'
        }
    },
    tipInsurance(event) {
        console.log(event)
        console.log(event.currentTarget.top)
        this.setData({
            isTipInsurance: true,
            tipTop: event.currentTarget.offsetTop + 20,
            tipLeft: 110
        })
    },
    cancelTipInsurance() {
        // console.log('点击啦')
        if (this.data.isTipInsurance) {
            this.setData({
                isTipInsurance: false
            })
        }
    },
    // 取消投保
    onCancelInsure(event) {
        const {
            id,
            index
        } = event.currentTarget.dataset
        let second = ''
        confirm('确认取消投保吗？').then(() => {
            second = this.data.workers[index].countDown
            if (second > 0) {
                cancelInsure({
                    id: id
                }).then(() => {
                    toast('已取消投保')
                    this.setData({
                        ['workers[' + index + '].countDown']: false
                    })
                })
            } else {
                toast('当前已完成投保')
            }
        })
        console.log(id, index, 'event')
    },
    // 下载保单pdf
    previewInsurance(event) {
        getInsurancePdf({
            id: this.data.workers[event.detail].wesureRecordId
        }).then(pdf => {
            if (wx.canIUse('openDocument')) {
                const projectName = this.data.workers[event.detail].workerName + this.data.date + '保单.pdf'
                openDocument(pdf, projectName).then(() => {}, () => {
                    this.setData({
                        copyLinkStatus: true,
                        copyLinkContent: pdf
                    })
                })
            } else {
                this.setData({
                    copyLinkStatus: true,
                    copyLinkContent: pdf
                })
            }
        })
    },
    async onConfirmInsure(event) {
        const enterpriseList = await getInsuranceEnterprise({
            insureCompanyType: 'insure_type_rrb'
        })
        const enterpriseIndex = await enterpriseList.filter(item => item.id === this.data.companyId)
        console.log(enterpriseIndex, 'enterpriseIndex')
        if (enterpriseIndex.length === 0) {
            app.toast('当前派遣单位状态异常,请检查')
            return
        } else {
            const programmeList = await getInsurePlan({
                serveCompanyId: this.data.companyId
            })
            const programmeIndex = programmeList.filter(item => item.id === this.data.industryPlanId)
            console.log(programmeIndex, 'programmeIndex')
            // wesurePlanName this.data.wesureTypeName
            if (programmeIndex.length === 0) {
                app.toast('方案不存在，请重新发起保单')
                return
            } else if (programmeIndex[0].industryPlanName !== this.data.wesureTypeName) {
                app.toast('当前方案已被修改，请重新发起保单')
                return
            }
        }
        if (this.data.isDeleteSeverCompany) {
            app.toast('派遣企业已被删除')
            return
        }
        console.log(this.data.already, '确定确定确定')
        if (this.data.createUserId !== user.userId) {
            app.toast('仅创建者可操作')
            return
        }
        // 前后端的约定 已投保的人员在上面 所以啊需要判断第一个就可以了
        if (this.data.workers[0].alreadyInsuredProjectId !== null) {
            app.toast('人员列表中存在已投保人员，请删除已投保人员后提交')
            return
        }
        if (this.data.workers.length === 0) {
            app.toast('暂无人员，不可投保')
            return
        }
        app.confirm('确认投保吗？\r\n温馨提示，出险后超过48小时不可报案').then(async () => {
            const result = await determineInsure({
                projectId: this.data.projectId
            })
            console.log(result, 'result')
            if (result?.code && result?.code === 2) {
                app.toast('已有人三小时内已投保')
                setTimeout(() => {
                    this.onShow()
                }, 1500)
                return
            }
            pageNum = 1
            notPage = false
            this.setData({
                workers: []
            })
            await this.getProject()
            await this.getProjectWorker()
            app.toast('投保成功')
        })
    },

    async onConfirmInsureAgain(event) {
        // app.toast('')
        // 获取方案列表
        const enterpriseList = await getInsuranceEnterprise({
            insureCompanyType: 'insure_type_rrb'
        })
        const enterpriseIndex = await enterpriseList.filter(item => item.id === this.data.companyId)
        console.log(enterpriseIndex, 'enterpriseIndex')
        if (enterpriseIndex.length === 0) {
            app.toast('当前派遣单位状态异常,请检查')
            return
        } else {
            const programmeList = await getInsurePlan({
                serveCompanyId: this.data.companyId
            })
            const programmeIndex = programmeList.filter(item => item.id === this.data.industryPlanId)
            console.log(programmeIndex, 'programmeIndex')
            // wesurePlanName this.data.wesureTypeName
            if (programmeIndex.length === 0) {
                app.toast('方案不存在，请重新发起保单')
                return
            } else if (programmeIndex[0].industryPlanName !== this.data.wesureTypeName) {
                app.toast('当前方案已被修改，请重新发起保单')
                return
            }
        }
        const result = await expressInsurance({
            id: this.options?.id,
            insureCompanyType: this.data.insureCompanyType
        })
        console.log(result, '再次快捷投保成功')
        let id = result.data
        let isAgain = 5
        wx.redirectTo({
            url: '/packageInsurance/pages/insurance-insure-detail/insurance-insure-detail?id=' + id + '&isAgain=' + isAgain,
        })
    },

    onAddManualStatus() {
        this.setData({
            pageNum: 1,
            isManualAdd: true
        })
    },
    onCancelManual() {
        this.setData({
            isManualAdd: false
        })
    },
    // 手动添加用户
    onAddManual(event) {
        if (!event.detail.name) {
            app.toast('请输入员工姓名')
            return
        }
        if (!/^\d{17}[\dXx]$/.test(event.detail.cardNo)) {
            app.toast('请输入正确的身份证号码')
            return
        }
        console.log((new Date().getFullYear() - Number(event.detail.cardNo.slice(6, 10))), '打印年龄')
        if ((new Date().getFullYear() - Number(event.detail.cardNo.slice(6, 10))) > 65 || (new Date().getFullYear() - Number(event.detail.cardNo.slice(6, 10))) < 16) {
            app.toast('仅支持16-65岁之内，没有手机的员工投保')
            return
        }
        manualAddWorker({
            projectId: this.data.projectId,
            idCardNo: event.detail.cardNo,
            workerName: event.detail.name.replace(/\./g, '·')
        }).then(() => {
            app.toast('添加成功!', 'success')
            setTimeout(() => {
                pageNum = 1
                notPage = false
                this.setData({
                    workers: [],
                    isManualAdd: false
                })
                this.getProjectWorker()
            }, 1000)
        })
    },
    // 去项目中导入人员
    goProjectImport() {
        wx.navigateTo({
            url: '/packageInsurance/pages/project-list-import/project-list-import?id=' + this.data.projectId,
        })
    }
})